var customerId = '';//时时获取对应项目标识
//临采商品管理-发送临采商品变更消息  sendSyncTempSkuMessage

function tempSendSyncMessageInfo(type, skuId,customerId) {
    // messageType 10：价格  20：商品信息 30：上下架
    // skuId 商品ID
    // customerId  渠道唯一标识
    var params = {
        messageType: type,
        skuCode: skuId,
        customerId: customerId
    }
    var successCallBack = function (data) {
        if (data.errorCode == 0) {
            layer.msg('操作成功', {offset: 't', icon: 1})
        } else {
            layer.msg('操作失败', {offset: 't', icon: 2})
        }
    }
    return web.doAjax(root.dockingplatform.sendSyncTempSkuMessage, 'post', params, successCallBack, 1)
}

// 渲染对应的表格
function renderShanDataTable(dataSource) {
    var shanTable = $('#shanDataTable').dataTable(); // 初始化dataTable，清空上一个值
    shanTable.fnClearTable(); //清空一下table
    shanTable.fnDestroy(); //还原初始化了的datatable
    $("#shanDataTable").DataTable({
        "autoWidth": false,
        "ordering": false,
        "searching": true,
        "paging": false,
        "retrieve": true,
        "destroy": true,
        "bAutoWidth": true,
        "bLengthChange": true,
        "aLengthMenu": [50, 25, 10, 5],
        "oLanguage": {
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
            "sInfoEmpty": "没有数据",
            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            },
            "sZeroRecords": "没有检索到数据",
            "sProcessing": "<img src='./loading.gif' />"
        },
        data: dataSource,
        columnDefs: [
            {
                "visible": true,
                "targets": 0
            },
            {
                "render": function (data, type, row, meta) {
                    var val = row[3] + '<br/>' + row[4] + '<br/>' + row[5];
                    return val;
                },
                "targets": 0
            },
            {
                "render": function (data, type, row, meta) {
                    var val = row[6];
                    return val;
                },
                "targets": 1
            },
            {
                "render": function (data, type, row, meta) {
                    var val = row[7];
                    return val;
                },
                "targets": 2
            },
            {
                "render": function (data, type, row, meta) {
                    var val = '<span id="' + row[0] + '" onmouseover="showAll(' + row[0] + ',' + row[13] + ')" onmouseout="hideAll(' + row[13] + ')" style="overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp:2; line-clamp:2; -webkit-box-orient: vertical;">' + row[8] + '</span>';
                    val += '<div class="' + row[13] + '" style="position:absolute;left: 650px; background: #fff;padding:10px;border:1px solid #ccc;display:none;"></div>';
                    return val;
                },
                "targets": 3
            },
            {
                "render": function (data, type, row, meta) {
                    var val = "";
                    if (row[9] == null || row[9] == undefined || row[9] == "") {
                        val = "";
                        return val
                    } else {
                        var val = '<span id="' + row[13] + '" onmouseover="showAll(' + row[13] + ',' + row[0] + ')" onmouseout="hideAll(' + row[0] + ')" style="overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp:2; line-clamp:2; -webkit-box-orient: vertical;">' + row[9] + '</span>';
                        val += '<div class="' + row[0] + '" style="position:absolute;right: 300px; background: #fff;padding:10px;border:1px solid #ccc;display:none;"></div>';
                        return val;
                    }
                },
                "targets": 4
            },
            {
                "render": function (data, type, row, meta) {
                    var row10 = row[10];
                    if (row[10] == null || row[10] == undefined) {
                        row10 = '';
                    }
                    var val = '成本价：' + row10 + '元<br/>VIP价：' + row[11] + '元';
                    return val;
                },
                "targets": 5
            },
            {
                "render": function (data, type, row, meta) {
                    var date = row[12];
                    var split = date.split(" ");
                    var val = split[0];
                    return val;
                },
                "targets": 6
            },
            {
                "render": function (data, type, row, meta) {
                    var val = "";
                    if (row[15] == 1) {
                        val = '成功';
                    } else if (row[15] == 2) {
                        val = '失败';
                    } else if (row[15] == 3) {
                        val = '移除';
                    } else {
                        val = '待推送'
                    }
                    return val;
                },
                "targets": 7
            },
            {
                "render": function (data, type, row, meta) {
                    var val = row[17];
                    return val;
                },
                "targets": 8
            },
            // 审核状态
            {
                "render": function (data, type, row, meta) {
                    var checkStatus = row[18] ? row[18] : '';
                    return '<span>' + checkStatus + '</span>'
                },
                "targets": 9
            },
            // 上架状态
            {
                "render": function (data, type, row, meta) {
                    var shelvesStatus = row[19] ? row[19] : '';
                    return '<span>' + shelvesStatus + '</span>'
                },
                "targets": 10
            },
            {

                "render": function (data, type, row, meta) {
                    var htmlStr = '';
                    var str = '<div>' +
                        '<span style="cursor: pointer;color: #1476e5;margin-right: 8px" onclick="updateInformation(20,\'' + row[0] + '\',\'' + row[16] + '\')">更新价格</span>' +
                        '<span style="cursor: pointer;color: #1476e5;" onclick="updateInformation(10,\'' + row[0] + '\',\'' + row[16] + '\')">更新信息</span>' +
                        '</div>'
                    if (row[15] == 1) {
                        htmlStr = str + '<div>' +
                            '<span class="powerButton 610" onclick="procure_edit(\'临采商品详情\', \'procureGoodsManageDetails.html\',\'' + row[0] + '\',\'' + row[16] + '\')" style="color: #1476e5;cursor: pointer;margin-right:8px">取消对接</span>' +
                            '<span style="cursor: pointer;color: #1476e5" onclick="repeatSendSku(\'' + row[0] + '\',\'' + row[16] + '\',\'' + row[13] + '\')">重新推送</span>' +
                            '</div>'
                    } else {
                        htmlStr = str + '<div>' +
                            '<span style="cursor: pointer;color: #1476e5;" onclick="repeatSendSku(\'' + row[0] + '\',\'' + row[16] + '\',\'' + row[13] + '\')">重新推送</span>' +
                            '</div>'
                    }
                    return htmlStr

                },
                "targets": 11
            },
        ],
    });
}

// 变更消息操作  更新价格  更新信息  更新上下架
function updateInformation(type, skuId,customerId) {
    layer.confirm('请确认同步该SKU的消息变更通知，并确保渠道可获取。', {
        btn: ['确认', '取消'],//按钮
        offset: 't'
    }, function () {
        tempSendSyncMessageInfo(type, skuId,customerId)
    }, function () {
    });
}

//渠道
ascription2()

function ascription2() {
    $.ajax({
        type: "post",
        url: root.dockingplatform.allChannelConfig,
        cache: false,  //禁用缓存
        dataType: "json",
        data: {},
        success: function (data) {
            console.log(data)
            if (data.errorCode == "0") {
                var dataInter = data.data;
                var interText = doT.template($("#ascription_bob").text());
                $("#ascription_lsit").html(interText(dataInter));
                if (localStorage.getItem("chooseData") != null) {
                    var chooseData = JSON.parse(localStorage.getItem("chooseData"));
                    $("#ascription_lsit").val(chooseData.ascription_lsit);
                    // localStorage.removeItem("chooseData");
                }
            }
        },
        error: function () {
            $.Huimodalalert('失败！', 2000);
        }
    });


}

var dataSource = new Array();
//table的数据源
var table; //table对象
dataSource = [];

function goodsList(data) {
    if (dataSource.length > 0) {
        dataSource.splice(0, dataSource.length); //清空数组
    }
    if (data.data != null) {
        $.each(data.data.result, function (i, field) {
            var rowData = new Array();
            rowData.push(field.skuCode);//0
            rowData.push(field.skuName);//1
            rowData.push(field.specifications);//2

            /* rowData.push(field.product_code);//商品码
             rowData.push(field.old_sku_name);
             rowData.push(field.old_specifications);*/
            rowData.push(field.skuCode);//商品码3
            rowData.push(field.skuName);//4
            rowData.push(field.specifications);//5
            rowData.push(field.brandName);//6
            rowData.push(field.unitName);//7
            rowData.push(field.supplierName);//8
            rowData.push(field.customerName);//9
            rowData.push(field.costPrice);//10
            rowData.push(field.price);//11
            var time = format(field.createdTime);
            rowData.push(time);//12
            rowData.push(field.skuId);//13
            rowData.push(field.virtualStock);//14
            rowData.push(field.sendStatus);  //第15个数
            rowData.push(field.customerId);  //第16个数
            rowData.push(field.sendTime);  //第17个数
            /* 陕建项目改造 */
            /* 审核状态  18*/
            rowData.push(field.channelAuditStatusDesc);//渠道审核状态描述
            /* 上架状态 19*/
            rowData.push(field.channelPutStatusDesc);//渠道上架状态的描述
            /*  /!* 售价 20*!/
              rowData.push(field.salePrice);//售价*/

            dataSource.push(rowData);
        });
    }


  /*  if (customerId == 'DJ00000006') {
        renderShanDataTable(dataSource);
    } else {
        initDataTable(dataSource);
    }*/
    renderShanDataTable(dataSource);
    power();
}


function getTemporaryGoodsList() {
    if ($("#ascription_lsit option:selected").val() == null || $("#ascription_lsit option:selected").val() == undefined || $("#ascription_lsit option:selected").val() == '') {
        layer.msg('渠道商不能为空！', {icon: 5, time: 1000});
        return false;
    }
    $.ajax({
        contentType: 'application/json',
        url: root.dockingplatform.selectInquirySku,
        cache: false, //禁用缓存
        type: "POST",
        data: JSON.stringify({
            rows: 20,
            curPage: 1,
            skuCode: $("#skuCode").val(),
            code: $("#code").val(),
            skuName: $("#productName").val(),
            oldSkuName: $("#oldProducrName").val(),
            specifications: $("#specificationsName").val(),
            oldSpecifications: $("#oldSpecificationsName").val(),
            brandName: $("#brand").val(),
            supplierName: $("#supplier").val(),
            customerName: $("#inquiryCustomer").val(),
            companyName: $("#createCompany").val(),
            departmentName: $("#createDepartment").val(),
            creationPersonName: $("#createBy").val(),
            createdTimeStart: $("#timemin").val(),
            createdTimeEnd: $("#timemax").val(),
            sendStatus: parseInt($("#selectVal1 option:selected").val()),
            channelId: $('#ascription_lsit option:selected').val(),
            /*陕建改造*/
            channelPutStatus: $('#channelShelvesStatus option:selected').val(), // 渠道上架状态
            channelAuditStatus: $('#channelCheckStatus option:selected').val()//渠道审核状态

        }),
        success: function (data) {
            goodsList(data);
            totalPage = data.data ? data.data.totalPage : 0;
            $('.M-box3').pagination({
                pageCount: totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        contentType: 'application/json',
                        url: root.dockingplatform.selectInquirySku,
                        cache: false, //禁用缓存
                        type: "POST",
                        data: JSON.stringify({
                            rows: 20,
                            curPage: api.getCurrent(),
                            skuCode: $("#skuCode").val(),
                            code: $("#code").val(),
                            skuName: $("#productName").val(),
                            oldSkuName: $("#oldProducrName").val(),
                            specifications: $("#specificationsName").val(),
                            oldSpecifications: $("#oldSpecificationsName").val(),
                            brandName: $("#brand").val(),
                            supplierName: $("#supplier").val(),
                            customerName: $("#inquiryCustomer").val(),
                            companyName: $("#createCompany").val(),
                            departmentName: $("#createDepartment").val(),
                            creationPersonName: $("#createBy").val(),
                            createdTimeStart: $("#timemin").val(),
                            createdTimeEnd: $("#timemax").val(),
                            sendStatus: parseInt($("#selectVal1 option:selected").val()),
                            channelId: $('#ascription_lsit option:selected').val(),
                            /*陕建改造*/
                            channelPutStatus: $('#channelShelvesStatus option:selected').val(), // 渠道上架状态
                            channelAuditStatus: $('#channelCheckStatus option:selected').val()//渠道审核状态
                        }),
                        success: function (data) {
                            goodsList(data);
                        }
                    });
                }
            });
        }
    });
}

function repeatSendSku(skuCode, customerId, skuId) {
    // 查询商品信息,增加商品主图、商品详情校验
    var isCheckProductPass = true;
    var productMessage = "请完善商品信息：";
    $.ajax({
        url: root.goodsInter.goods_temporaryProductDetail,
        cache: false, //禁用缓存
        type: "POST",
        dataType: "json",
        async: false,
        data: {
            skuId: skuId
        },
        success: function (data) {
            if (data.errorCode == 0) {
                console.log(data);
                var obj = data.data;
                productMessage = productMessage + '<br/>商品[' + obj.sku_code + ']';
                // 增加名称校验
                if (obj.sku_name === null || obj.sku_name === undefined || obj.sku_name.trim() === "") {
                    productMessage = productMessage + '名称/';
                    isCheckProductPass = false;
                }
                // 增加规格校验
                if (obj.specifications === null || obj.specifications === undefined || obj.specifications.trim() === "") {
                    productMessage = productMessage + '规格/';
                    isCheckProductPass = false;
                }
                // 增加主图校验
                if (obj.tempPurchaseSkuImg === null || obj.tempPurchaseSkuImg === undefined || obj.tempPurchaseSkuImg.length === 0) {
                    productMessage = productMessage + '主图/';
                    isCheckProductPass = false;
                }
                // 增加详情校验
                if (obj.detail === null || obj.detail === undefined || obj.detail.trim() === "") {
                    productMessage = productMessage + '详情';
                    isCheckProductPass = false;
                }
            }
        }
    });
    if (!isCheckProductPass) {
        layer.msg(productMessage, {icon: 5, time: 2000});
        return false;
    }

    $.ajax({
        url: root.dockingplatform.repeatInquirySku,
        cache: false,  //禁用缓存
        type: "POST",
        data: {
            "customerId": customerId,
            "skuCode": skuCode //code码
        },
        success: function (data) {
            if (data.errorCode == 0) {
                showmsg("已加入重推队列！", 6);
            }
        },
        error: function (result) {
            $.Huimodalalert(data.msg, 2000);
        }
    });
}

// 提示信息
function showmsg(msg, icon) {
    layer.msg(msg, {
        icon: icon,
        time: 2000
    }, function () {
        if (icon == 6) {
            //location.replace(location.href);
            getTemporaryGoodsList();
        }
    });
}

function procure_edit(title, url, skuCode, customerId) {
    var formData = new FormData();
    formData.append('customerId', customerId);
    formData.append('skuCode', skuCode);
    $.ajax({
        type: "post",
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        url: root.dockingplatform.cancelInquirySku,
        data: formData,
        // data: {"page":"0","size":"3","cartonDetailNum":id,"cartoonId":cartoonId},//或者这样写进去
        success: function (result) {
            if (result.errorCode == 0) {
                $.Huimodalalert('取消对接成功！', 2000);
                /*location.replace(location.href)*/
                getTemporaryGoodsList();
            } else {
                $.Huimodalalert(result.msg, 2000);
            }


        },
        error: function (result) {
            $.Huimodalalert(result.msg, 2000);
        }
    });


    /*$.ajax({

        url: root.dockingplatform.cancleInquirySku,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: 'application/json',
        data: {
            "skuCode":skuCode,
            "customerId":customerId
        },
        success: function (data) {
            if(data.errorCode=="0") {
                var dataInter=data.data.result;
                var interText = doT.template($("#ascription_bob").text());
                $("#ascription_lsit").html(interText(dataInter));
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });*/
}

function showAll(code, id) {
    $("." + id).show();
    $("." + id).html($("#" + code).html());
}

function hideAll(id) {
    $("." + id).hide();
}

//临采商品导出
function exportInquirySkuExcel(){
    var channelId = $('#ascription_lsit option:selected').val();
    if (!channelId) {
        layer.msg('渠道商不能为空！', {icon: 5, time: 1000});
        return false;
    }
    var url = root.dockingplatform.exportInquirySkuExcel 
    + "?skuCode=" + $("#skuCode").val() + "&skuName=" + $("#productName").val() + "&specifications=" + $("#specificationsName").val()
    + "&brandName=" + $("#brand").val() + "&supplierName=" + $("#supplier").val() + "&customerName=" + $("#inquiryCustomer").val()
    + "&companyName=" + $("#createCompany").val() + "&departmentName=" + $("#createDepartment").val() + "&creationPersonName=" + $("#createBy").val()
    + "&createdTimeStart=" + $("#timemin").val() + "&createdTimeEnd=" + $("#timemax").val() + "&sendStatus=" + parseInt($("#selectVal1 option:selected").val())
    + "&channelId=" + $('#ascription_lsit option:selected').val() + "&channelPutStatus=" + $('#channelShelvesStatus option:selected').val() 
    + "&channelAuditStatus=" + $('#channelCheckStatus option:selected').val();
    window.location.href = url;
}